package com.yupi.yupao.controller;

import cn.hutool.core.date.DateTime;
import com.yupi.yupao.common.BaseResponse;
import com.yupi.yupao.common.ErrorCode;
import com.yupi.yupao.common.ResultUtils;
import com.yupi.yupao.exception.BusinessException;
import com.yupi.yupao.model.domain.Message;
import com.yupi.yupao.model.domain.Team;
import com.yupi.yupao.model.domain.User;
import com.yupi.yupao.model.domain.request.MessageAddRequest;
import com.yupi.yupao.model.domain.request.TeamAddRequest;
import com.yupi.yupao.service.MessageService;
import com.yupi.yupao.service.UserService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.Date;
import java.util.List;

@RestController
@RequestMapping("/message")
@CrossOrigin(origins = {"https://www.dynamic-qhe.com.cn","http://localhost"},allowCredentials = "true")
@Slf4j
public class MessageController {

    @Resource
    private MessageService messageService;

    @Resource
    private UserService userService;

    /**
     * 发送消息
     * @param messageAddRequest
     * @param request
     * @return
     */
    @PostMapping("/add")
    public BaseResponse<Boolean> addMessage(@RequestBody MessageAddRequest messageAddRequest, HttpServletRequest request){
        if (messageAddRequest == null){
            throw new BusinessException(ErrorCode.NULL_ERROR);
        }

        User loginUser = userService.getLoginUser(request);

        Message message = new Message();

        message.setFrom_id(loginUser.getId());

        // 这个函数，是吧前面的字段的值，赋值给后面的字段
        BeanUtils.copyProperties(messageAddRequest,message);
        //会话id是string类型的，始终是小ID在前，大id在后
        if (message.getFrom_id() < message.getTo_id()) {
            message.setConversation_id(message.getFrom_id() + "_" + message.getTo_id());
        } else {
            message.setConversation_id(message.getTo_id() + "_" + message.getFrom_id());
        }

        message.setCreate_time(new Date());
        boolean result = messageService.insertMessage(message);

        return ResultUtils.success(result);

    }

    /**
     * 根据已经登录的用户的id和传来的接受信息的用户id参数，拼接成会话id，进而进行查询
     * @param to_id
     * @param request
     * @return
     */
    @GetMapping("/get")
    public BaseResponse<List<Message>> getMessageById(int to_id,HttpServletRequest request){
        //判空数据
        if(to_id < 0){
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        User loginUser = userService.getLoginUser(request);

        List<Message> list = messageService.getMessageByCid(to_id, loginUser);

        if (list == null){
            return ResultUtils.success(null);
        }

        return ResultUtils.success(list);
    }


}
